#include "Device/NixieTube.h"
#include "Common/BitOpr.h"
#include "Hardware/IO.h"
#include <string.h> //memset所在头文件
#include "Hardware/Timer.h"

#define NixiePort P0 //数码管所在IO口
#define NixieSelectPort P2 //数码管位选段选所在IO口
#define BitSelect 7 //位选
#define SegSelect 6 //段选

byte code BitSelectCode[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f}; //位选码表

//共阴极码表
byte code NixieCharData[]={ 
                0x3F,  //"0"
                0x06,  //"1"
                0x5B,  //"2"
                0x4F,  //"3"
                0x66,  //"4"
                0x6D,  //"5"
                0x7D,  //"6"
                0x07,  //"7"
                0x7F,  //"8"
                0x6F,  //"9"
				0x00,  //熄灭
				0x80   //'.'
};
#define Point (NixieCharData[11])
#define Blank (NixieCharData[10])

enum NIXIESTATUS
{
	CLOSE=0,
	OPEN
};

char m_Nixie[8];

void NixieInit()
{
	PortSet(NixieSelectPort,CLOSE,SegSelect); //关闭段选
	PortSet(NixieSelectPort,CLOSE,BitSelect);//关闭位选
}

void NixieSetChar(char c,uint8 pos)
{
	if(pos>7)
		return;
	if(c>='0' && c<='9')
	{
		m_Nixie[pos]=( (m_Nixie[pos] & Point) | NixieCharData[c-'0'] ); // 先取出'.'的状态,然后与现在的字符相与
	}
}


void NixieSetPoint(uint8 pos)
{
	if(pos>7)
		return;
	m_Nixie[pos]|=Point;
}

void NixieSetString(char str[],uint8 count,uint8 pos)
{
	uint8 i;
	if(count>8)
		return;
	for(i=0;i<count;++i)
	{
		NixieSetChar(str[i],pos+i);
	}
}


void NixieSetPointArray(uint8 arr[],uint8 count)
{
	uint8 i;
	if(count>8)
		return;
	for(i=0;i<count;++i)
	{
		NixieSetPoint(arr[i]);
	}
}


void NixieClear(uint8 pos)
{
	if(pos<8)
		m_Nixie[pos]=Blank;
}


void NixieClearAll()
{
	memset(m_Nixie,Blank,sizeof(m_Nixie));
}


void NixieClearArray(uint8 pos[],uint8 count)
{
	uint8 i;
	if(count>8)
		return;
	for(i=0;i<count;++i)
	{
		NixieClear(pos[i]);
	}
}


void NixieSetNumber(uint16 number)
{
	uint8 res[8];
	uint8 i=0,length=0;
	uint8 tmp;
	memset(res,0,sizeof(res));
	
	NixieClearAll();
	if(number==0)
	{
		NixieSetChar('0',0);
		return;
	}
	
	while(number)
	{
		res[i++]=number%10+0x30;
		number/=10;
	}
	
	//倒置
	for(length=i,i=0;i<length/2;++i)
	{
		tmp=res[i];
		res[i]=res[length-i-1];
		res[length-i-1]=tmp;
	}
	for(i=0;i<length;++i)
	{
		NixieSetChar(res[i],i);
	}
}


void NixieShow()
{
	uint8 i;
	for(i=0;i<sizeof(m_Nixie);++i)
	{
		if(m_Nixie[i]!=Blank) //只要不是空 就表示有需要显示的字符
		{
			NixiePort=BitSelectCode[i]; //先送位选
			PortSet(NixieSelectPort,OPEN,BitSelect);//打开位选
			PortSet(NixieSelectPort,CLOSE,BitSelect);//关闭位选
			
			NixiePort=m_Nixie[i]; //送段选,需要显示的二进制
			PortSet(NixieSelectPort,OPEN,SegSelect); //打开段选
			PortSet(NixieSelectPort,CLOSE,SegSelect); //关闭段选
			
			Delay(1); //延时1ms,以免乱码
		} 
	}
}